package com.ym.manager.admin.merchant;

import com.google.gson.Gson;
import com.ym.manager.admin.merchant.model.Merchant;
import com.ym.manager.admin.merchant.model.MerchantExpressInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

//@Service
public class MerchantManager implements Runnable{


    @Autowired
    private MerchantDao merchantDao;
    /*店家map*/
    private Map<Integer,Merchant> merchantMap = new HashMap<>();

    /**
     * 获取店家信息
     * @param merchant_id 店家id
     * @return
     */
    public Merchant getMerchant(int merchant_id){
        return merchantMap.get(merchant_id);
    }


    @PostConstruct
    public void init() {
        load();
        new Thread(this).start();
    }

    @Override
    public void run() {
        try {
            while (true) {
                Thread.sleep(1000*60*2);
                load();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void load() {
        List<Merchant> list = merchantDao.MerchantList();
        if(null == list || 0 >= list.size()){
            merchantMap = new HashMap<>();
            return;
        }
        Gson gson = new Gson();
        list = list.stream().peek(x->{
            String expressJson = x.getExpressJson();
            x.setMerchantExpressInfo(gson.fromJson(expressJson, MerchantExpressInfo.class));
        }).collect(Collectors.toList());
        merchantMap = list.stream().collect(Collectors.toMap(Merchant::getId,Function.identity()));
    }
}
